import axios from 'axios'
import Element from 'element-ui'
import router from './router'

// 配置请求的根路径
axios.defaults.baseURL = 'http://localhost:80/api/'
// axios请求拦截  前置拦截
axios.interceptors.request.use(config => {
  // 在最后必须return config
  const token = window.sessionStorage.getItem('token')
  if (token) {
    config.headers.Authorization = token
  }
  return config
})
axios.interceptors.response.use(
  response => {
    const res = response.data
    // console.log(res)
    if (res.code === 200) {
      return response
    } else {
      Element.Message.error('密码不正确', {
        duration: 2 * 1000
      })
      return Promise.reject(response.data.msg)
    }
  },
  error => {
    console.log(error)
    if (error.response.data) {
      error.message = error.response.data.msg
    }
    if (error.response.code === 401) {
      // 清空info
      // 跳转到登录页
      router.push('/login')
    }
    Element.Message.error(error.message, {
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)
